package com.itheima.java.ai.langchin4j.controller;

import com.itheima.java.ai.langchin4j.config.JwtUtil;
import com.itheima.java.ai.langchin4j.entity.Appointment;
import com.itheima.java.ai.langchin4j.server.AppointmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/appointments")
@Tag(name = "预约管理", description = "预约相关接口")
public class AppointmentController {
    
    // 默认用户策略 - 权限控制移除后使用
    private static final Long DEFAULT_USER_ID = 1L;
    
    @Autowired
    private AppointmentService appointmentService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/check")
    @Operation(summary = "检查预约是否存在")
    public Appointment checkAppointment(@RequestBody Appointment appointment) {
        return appointmentService.getOne(appointment);
    }
    
    @PostMapping
    @Operation(summary = "创建预约")
    public Map<String, Object> createAppointment(
            @RequestBody Map<String, Object> request,
            HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 参数验证
            String validationError = validateCreateAppointmentParams(request);
            if (validationError != null) {
                response.put("success", false);
                response.put("message", validationError);
                return response;
            }
            
            // 使用默认用户ID - 权限控制已移除
            Long userId = DEFAULT_USER_ID;
            
            // 安全地获取参数
            Long doctorId = Long.valueOf(request.get("doctorId").toString());
            Long scheduleId = Long.valueOf(request.get("scheduleId").toString());
            LocalDate appointmentDate = LocalDate.parse(request.get("appointmentDate").toString());
            String timeSlot = request.get("timeSlot").toString();
            String symptoms = request.get("symptoms").toString();
            
            Appointment appointment = appointmentService.createAppointment(
                    userId, doctorId, scheduleId, appointmentDate, timeSlot, symptoms);
            
            response.put("success", true);
            response.put("data", appointment);
            response.put("message", "预约创建成功");
        } catch (NumberFormatException e) {
            response.put("success", false);
            response.put("message", "参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "预约创建失败: " + e.getMessage());
        }
        return response;
    }
    
    /**
     * 验证创建预约的参数
     * @param request 请求参数
     * @return 验证错误信息，如果验证通过返回null
     */
    private String validateCreateAppointmentParams(Map<String, Object> request) {
        if (request == null) {
            return "请求参数不能为空";
        }
        
        // 检查必需参数是否存在且不为null
        String[] requiredParams = {"doctorId", "scheduleId", "appointmentDate", "timeSlot", "symptoms"};
        for (String param : requiredParams) {
            Object value = request.get(param);
            if (value == null) {
                return "缺少必需参数: " + param;
            }
            if (value.toString().trim().isEmpty()) {
                return "参数不能为空: " + param;
            }
        }
        
        // 验证数字类型参数
        try {
            Object doctorId = request.get("doctorId");
            if (doctorId != null) {
                Long.valueOf(doctorId.toString());
            }
            
            Object scheduleId = request.get("scheduleId");
            if (scheduleId != null) {
                Long.valueOf(scheduleId.toString());
            }
        } catch (NumberFormatException e) {
            return "医生ID或排班ID格式错误，必须为数字";
        }
        
        // 验证日期格式
        try {
            Object appointmentDate = request.get("appointmentDate");
            if (appointmentDate != null) {
                LocalDate.parse(appointmentDate.toString());
            }
        } catch (Exception e) {
            return "预约日期格式错误，请使用YYYY-MM-DD格式";
        }
        
        return null; // 验证通过
    }
    
    @GetMapping("/my")
    @Operation(summary = "获取我的预约列表")
    public Map<String, Object> getMyAppointments(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 使用默认用户ID - 权限控制已移除
            Long userId = DEFAULT_USER_ID;
            
            List<Appointment> appointments = appointmentService.getUserAppointments(userId);
            response.put("success", true);
            response.put("data", appointments);
            response.put("message", "获取预约列表成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取预约列表失败: " + e.getMessage());
        }
        return response;
    }
    
    @GetMapping("/my/status/{status}")
    @Operation(summary = "根据状态获取我的预约")
    public Map<String, Object> getMyAppointmentsByStatus(
            @PathVariable("status") String status,
            HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 使用默认用户ID - 权限控制已移除
            Long userId = DEFAULT_USER_ID;
            
            List<Appointment> appointments = appointmentService.getUserAppointmentsByStatus(userId, status.toUpperCase());
            response.put("success", true);
            response.put("data", appointments);
            response.put("message", "获取预约列表成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取预约列表失败: " + e.getMessage());
        }
        return response;
    }
    
    @PutMapping("/{appointmentId}/cancel")
    @Operation(summary = "取消预约")
    public Map<String, Object> cancelAppointment(
            @PathVariable("appointmentId") Long appointmentId,
            HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 使用默认用户ID - 权限控制已移除
            Long userId = DEFAULT_USER_ID;
            
            boolean success = appointmentService.cancelAppointment(appointmentId, userId);
            if (success) {
                response.put("success", true);
                response.put("message", "预约取消成功");
            } else {
                response.put("success", false);
                response.put("message", "预约取消失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "预约取消失败: " + e.getMessage());
        }
        return response;
    }
    
    @PutMapping("/{appointmentId}/confirm")
    @Operation(summary = "确认预约")
    public Map<String, Object> confirmAppointment(@PathVariable("appointmentId") Long appointmentId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = appointmentService.confirmAppointment(appointmentId);
            if (success) {
                response.put("success", true);
                response.put("message", "预约确认成功");
            } else {
                response.put("success", false);
                response.put("message", "预约确认失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "预约确认失败: " + e.getMessage());
        }
        return response;
    }
}